<?php

namespace app\admin\controller;

use app\admin\model\Order;
use app\BaseController;
use think\facade\Db;
use think\App;
use think\cache\driver\Redis;

/**
 * @author xjw
 * @class:Taskachievement 定时任务=>业绩操作
 * @method:site_report  统计站点业绩
 * @method:person_report 统计运营业绩
 * @method:person_product_sales  运营产品销量
 */



class Taskachievement extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Order();
    }


    /**
     *   每月1日1点20分执行=>统计店铺业绩=>一个月
     */
    public function site_report($site_id = null)
    {
        $where2 = '1=1';
        $timedate = 'created_at';
        if (!empty($site_id)) {
            $siteReport = table('shopify_sitereport')->where('site_id', $site_id)->find();
            if (!empty($siteReport)) {
                $where2 = " site_id = '" . $siteReport['site_id'] . "' ";
                $lastmonth_start = $siteReport['timedate'];
                $lastmonth_end = mktime(23, 59, 59, date('m', $siteReport['timedate']), date('t', $siteReport['timedate']), date('Y', $siteReport['timedate']));
            } else {
                return error('参数错误');
            }
        } else {
            //上个月开始时间戳
            // $lastmonth_start = mktime(0, 0, 0, date('m') - 2, 1, date('Y'));
            // $lastmonth_end = mktime(23, 59, 59, date('m') - 1, 0, date('Y'));
            $lastmonth_start = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
            $lastmonth_end = mktime(23, 59, 59, date('m'), 0, date('Y'));
        }
        if(!empty(input('lastmonth_start')) && !empty(input('lastmonth_end'))){
            $lastmonth_start = input('lastmonth_start');
            $lastmonth_end = input('lastmonth_end');
        }
        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT site_id
,cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(material) AS decimal(15,2)) as material,currency
FROM qu_order
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
AND status = 'normal'
GROUP BY site_id
ORDER BY site_id ASC";
        $statistics = Db::query($sql);

        $siteReport = array();
        table('shopify_sitereport')
            ->where('timedate', $lastmonth_start)
            ->delete();
        foreach ($statistics as $statistic) {
            $arr['createtime'] = time();
            $arr['updatetime'] = time();
            $arr['freight'] = $statistic['freight'];
            $arr['material'] = $statistic['material'];
            $arr['timedate'] = $lastmonth_start;
            $arr['total_price'] = $statistic['total_price'];
            $arr['site_id'] = $statistic['site_id'];
            $arr['currency'] = $statistic['currency'];
            $siteReport = table('shopify_sitereport')->insert($arr);
        }

        if (!empty($siteReport)) {
            return success('操作成功', $siteReport);
        } else {
            return error('未找到相关订单');
        }
    }

    /** 
     * 
     * 每月, 1日 1点30分执行=>统计运营业绩
     * 
     */

    public function person_report($id = null)
    {
        if(!empty($id)){
            $personreport = table('shopify_personreport')->where('id', $id)->find();
            if(empty($personreport)){
                return 2;
            }
            $b_time = $personreport['timedate'];
            $firstday = date("Y-m-d", $b_time);
            $e_time = strtotime(date("Y-m-d", strtotime("$firstday +1 month")));
            $admin_id = $personreport['admin_id'];
        }else{
            $thismonth = date('m');
            $thisyear = date('Y');
            // if ($thismonth == 1) {
            //     $lastmonth = 11;
            //     $lastyear = $thisyear - 1;
            // } elseif ($thismonth == 2) {
            //     $lastmonth = 12;
            //     $lastyear = $thisyear - 1;
            // } else {
            //     $lastmonth = $thismonth - 2;
            //     $lastyear = $thisyear;
            // }
            if ($thismonth == 1) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            }else {
                $lastmonth = $thismonth - 1;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $b_time = strtotime($lastStartDay);
            $system_group_admin = table('system_group_admin')
                ->where('group_id', 5)
                ->select()->toarray();
        }
        if(!empty($system_group_admin)){
            foreach ($system_group_admin as $ka=>$va) {
                $arr = array();
                $arr['freight'] = 0;
                $arr['material'] = 0;
                $arr['advertising'] = 0;
                $arr['total_price'] = 0;
                $arr['profit'] = 0;
                $reportmonthtwo = table('shopify_personreport')
                    ->where('admin_id', $va['admin_id'])
                    ->where('timedate', $b_time)
                    ->find();
                if (empty($reportmonthtwo)) {
                    $arr['timedate'] = $b_time;
                    $arr['admin_id'] = $va['admin_id'];
                    $arr['createtime'] = time();
                    $arr['updatetime'] = time();
                    table('shopify_personreport')->insert($arr);
                }else{
                    $arr['updatetime'] = time();
                    table('shopify_personreport')->where('id',$reportmonthtwo['id'])->update($arr);
                }
            }
        }
        return 1;
    }

    /**
     *  三分钟执行=>运营产品销量
     * 
     */

    public function person_product_sales()
    {
        # TODO 状态需要确认
        $personproductsales = table('personproductsales')
            ->limit(200)
            ->where('status', 'hidden')
            ->where('notestatus', 'normal')
            ->order('updatetime asc')
            ->select()->toarray();
        $new = array();
        if (!empty($personproductsales)) {
            foreach ($personproductsales as $personproductsale) {
                $order = table('order')
                    ->where('tracking_number', $personproductsale['tracking_number'])
                    ->where('name', $personproductsale['name'])
                    ->find();
                if (!empty($order)) {
                    $order_quantitys = table('order_quantity')
                        ->field("a.*,b.material")
                        ->alias('a')
                        ->join('order_sku b', 'b.variants_id = a.variant_id', 'left')
                        ->where('order_id', $order['id'])
                        ->select()->toarray();
                    if (!empty($order_quantitys)) {
                        foreach ($order_quantitys as  $order_quantity) {
                            if (!empty($order_quantity['quantity']) && isset($order_quantity['quantity'])) {
                                if (!empty($new[$order_quantity['product_id']]) && isset($new[$order_quantity['product_id']])) {
                                    $new[$order_quantity['product_id']]['quantity'] += $order_quantity['quantity'];
                                } else {
                                    $new[$order_quantity['product_id']]['quantity'] = $order_quantity['quantity'];
                                }
                                $new[$order_quantity['product_id']]['sku'] = $order_quantity['sku'];
                                $new[$order_quantity['product_id']]['title'] = $order_quantity['title'];
                                $new[$order_quantity['product_id']]['material'] = $order_quantity['material'];

                                $new[$order_quantity['product_id']]['timedate'] = $order_quantity['timedate'];
                                $new[$order_quantity['product_id']]['user'] = $order_quantity['user'];
                                $new[$order_quantity['product_id']]['variants_id'] = $order_quantity['variant_id'];
                            }
                        }
                    }
                }
                $update['updatetime'] = time();
                $update['status'] = 'normal';
                table('personproductsales')
                    ->where('id', $personproductsale['id'])
                    ->update($update);
            }
        }
        $res = array();
        if (!empty($new)) {

            foreach ($new as $ka => $admin) {
                $personpurchase = table('personpurchase')
                    ->where('timedate', $admin['timedate'])
                    ->where('user', $admin['user'])
                    ->where('product_id', $ka)
                    ->find();
                if (!empty($personpurchase)) {
                    $update2['quantity'] = $personpurchase['quantity'] + $admin['quantity'];
                    $res[] = table('personpurchase')->where('product_id', $ka)->update($update2);
                } else {
                    $admin['product_id'] = $ka;
                    $res[] = table('personpurchase')->insert($admin);
                }
            }
        }
        return   success('操作成功', $res);
    }
    
    /** 
     * 
     * 归档
     * 
     */

    public function person_report_performance($id = null)
    {
        $shopify_personreport = table('shopify_personreport')
            ->where('id', $id)
            ->find();
        if(empty($shopify_personreport)){
            return 2;
        }
        $shopify_personreport_performance = table('shopify_personreport_performance')
            ->where('admin_id', $shopify_personreport['admin_id'])
            ->where('timedate', $shopify_personreport['timedate'])
            ->find();
        if(!empty($shopify_personreport_performance)){
            //已归档
            return 3;
        }else{
            $row1['performance'] = 1;
            $row1['updatetime'] = time();
            table('shopify_personreport')
                ->where('id',$shopify_personreport['id'])
                ->update($row1);

            unset($shopify_personreport['id']);
            unset($shopify_personreport['performance']);
            table('shopify_personreport_performance')
                ->insert($shopify_personreport);

            return 1;
        }
    }
}
